// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';
const find = _.find;

function isNumericStart(str) {
  return /^\d/.test(str);
}

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

Page({
  data: {
    // devices: [{MAC: "",
    // RSSI: -69,
    // advertisServiceUUIDs: [],
    // connectable: true,
    // deviceId: "FB:37:E1:0B:69:22",
    // localName: "76895768D",
    // name: "76895768D"}],
    devices:[],
    loading: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  openBluetoothAdapter() {
    //util.toastError('请先打开蓝牙');
    console.log('openBluetoothAdapter')
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log('openBluetoothAdapter fail', res)
        util.toastError('请先打开蓝牙'+res.errCode);
        if (res.errCode === 10001) {
          console.log('请先打开蓝牙1') //当蓝牙开关未开启或手机不支持蓝牙时，会返回错误 (errCode=10001)。
          // util.toastError('10001');
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    // if (this._discoveryStarted) {
    //   return
    // }
    // this._discoveryStarted = true
    this.setData({
      loading: true
    })
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  onBluetoothDeviceFound() {

    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (!isNumericStart(device.name || device.localName)) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        // let bf = device.advertisData.slice(2, 8);
        // console.log('bf', bf)
        // let mac = Array.prototype.map
        //   .call(new Uint8Array(bf), (x) => ("00" + x.toString(16)).slice(-2))
        //   .join(":");
        // mac = mac.toUpperCase();
        if (idx === -1) {

          data[`devices[${foundDevices.length}]`] = {
            ...device,
            // MAC: mac
          }
        } else {
          data[`devices[${idx}]`] = {
            ...device,
            // MAC: mac
          }
        }
        console.log(data)
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {
    const that = this
    // wx.chooseMessageFile({
    //   type: 'file',
    //   count: 1,
    //   extension: ['.bin'],
    //   success: function (res) {
    //     console.log(res)
    //     console.log(res.tempFiles[0].path)
    //     // that.setData({
    //     //   fileList:res.fileList
    //     // })
    //     wx.getFileSystemManager()
    //       .readFile({
    //         filePath: res.tempFiles[0].path, // 文件路径
    //         encoding: 'hex', // 返回格式
    //         success: (res) => {
    //           console.log(res.data)//返回content:13740长度，然后自己截取
    //         },
    //         fail(res) {
    //           console.log('fail', res);
    //         }
    //       });
    //   }
    // })
    // return
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name.length>8?ds.name.substr(0,8):ds.name;
    this.stopBluetoothDevicesDiscovery()
    wx.navigateTo({
      url: `/pages/items/items?deviceId=${deviceId}&name=${name}`
    })

    return
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })

  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
    this.setData({
      loading: false
    })
  },
})